import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

import user from "@/store/user";
import common from "@/store/common";
import menu from "@/store/menu";
import route from "@/store/route";

import { getSessionKey, setSession } from "@/utils/session";
const state = {
  ...common.state(),
  ...user.state(),
  ...menu.state(),
  ...route.state()
};
const mutations = {
  ...common.mutations,
  ...user.mutations,
  ...menu.mutations,
  ...route.mutations
};
const actions = {
  ...common.actions,
  ...user.actions,
  ...menu.actions,
  ...route.actions
};
const getters = {
  ...common.getters,
  ...user.getters,
  ...menu.getters,
  ...menu.getters
};

const store = new Vuex.Store({
  state,
  mutations,
  getters,
  actions
});

//vuex数据拦截 将需要长期存储的数据拦截，保存到浏览器
store.subscribe(({ type }, state) => {
  type = type.replace("SET_", "");
  if (/^USER$|^MENUFOLD$|^MENU$/.test(type)) {
    const key = getSessionKey(type);
    setSession(key, state[key], process.env.VUE_APP_TOKEN_EXPIRE);
  }
});

export default store;
